package com.yaorange.module.system.controller;

import com.yaorange.annotation.PermissionAnnotation;
import com.yaorange.module.system.entity.dto.SysUserQueryDTO;
import com.yaorange.module.system.service.SysUserService;
import com.yaorange.pojo.SysUser;
import com.yaorange.response.PageResult;
import com.yaorange.response.Result;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/sys/users")
@Slf4j
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取用户列表
     */
    @GetMapping
    @PermissionAnnotation("user:queryPage")
    public Result<PageResult<SysUser>> listUsers(SysUserQueryDTO sysUserQueryDTO) {
        PageResult<SysUser> pageInfo = sysUserService.findAllUsers(sysUserQueryDTO);
        return Result.success(pageInfo);
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    @PermissionAnnotation("user:queryById")
    public Result<SysUser> getUserById(@PathVariable Long id) {
        log.info("根据id获取用户详情:{}",id);
        SysUser user = sysUserService.findById(id);
        return Result.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    @PermissionAnnotation("user:save")
    public Result<?> createUser(@Valid @RequestBody SysUser user) {
        sysUserService.save(user);
        return Result.success();
    }

    /**
     * 更新用户信息
     */
    @PutMapping()
    @PermissionAnnotation("user:update")
    public Result<?> updateUser( @Valid @RequestBody SysUser userDetails) {
        sysUserService.update(userDetails);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PermissionAnnotation("user:deleteById")
    public Result<?> deleteUser(@PathVariable Long id) {
        sysUserService.deleteById(id);
        return Result.success();
    }

    /**
     *  为用户赋予角色
     * @param id 用户编号
     * @param roleIds  角色编号列表
     */
    @PostMapping("/{id}")
    @PermissionAnnotation("user:grantRole")
    public Result<?> grantRoles(@RequestBody List<Long> roleIds,@PathVariable Long id){
        sysUserService.grantRolesList(id,roleIds);
        return Result.success();
    }



    /**
     *  根据用户编号获取用户的角色列表
     */
    @GetMapping("/{userId}/roles")
    public Result<List<Long>> listRolesByUserId(@PathVariable Long userId) {
        List<Long> roleIds = sysUserService.findRoleListByUserId(userId);
        return Result.success(roleIds);
    }

}